﻿using System.Text.RegularExpressions;
namespace MyNanny
{
    public class Domain
    {

        public const string SearchExpression = @"^\s*((\#*)\s*(\d+\.\d+\.\d+\.\d+)\s+(.*?))?(\#(.*))?$";
        public const int Search_TheHostRecord = 1;
        public const int Search_EnabledFlag = 2;
        public const int Search_IPAddress = 3;
        public const int Search_HostName = 4;
        public const int Search_Comment = 5;
        public const int Search_CommentText = 6;

        public Domain(bool Enabled, string IP, string Host, string Comment)
        {
            this.Enabled = Enabled;
            this.IP = IP;
            this.Host = Host;
            this.Comment = Comment;
        }
        public Domain(string Comment)
        {
            this.Enabled = false;
            this.IP = null;
            this.Host = null;
            this.Comment = Comment;
        }


        public string Comment;


        public bool Enabled;

        public string IP;

        public string Host;
        public bool IsEmpty
        {
            get
            {
                return string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(Host);
            }
        }

        public bool IsComment
        {
            get
            {
                return string.IsNullOrEmpty(IP) && string.IsNullOrEmpty(Host) && !string.IsNullOrEmpty(Comment);
            }
        }

        public override string ToString()
        {
            if (IsComment) return Comment;
            return string.Format("{0}{1}\t{2}{3}", Enabled ? "" : "#", IP, Host, (string.IsNullOrEmpty(Comment)) ? string.Empty : string.Format("\t#{0}", Comment));
        }

        public static Domain Parse(string record)
        {
            Match match = Regex.Match(record, Domain.SearchExpression, RegexOptions.Compiled);
            string comment = match.Groups[Domain.Search_Comment].Value.Trim();

            return new Domain(
                            match.Groups[Domain.Search_EnabledFlag].Length == 0,
                            match.Groups[Domain.Search_IPAddress].Value.Trim(),
                            match.Groups[Domain.Search_HostName].Value.Trim(),
                            (comment.Length > 1) ? comment.Substring(1) : comment);
        }
    }
}
